<?php

declare(strict_types=1);

namespace App\Command;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\Redis\Redis;
use Psr\Container\ContainerInterface;

/**
 * @Command
 */
#[Command]
class Jst extends HyperfCommand
{
    protected ContainerInterface $container;
    protected $client;
    protected $redis;

    private $dept_code = 1004; //科室
    private $visit_date = '2024-09-19'; //日期

    private $patient_code = 13424278; //就诊人
    //有效期5分钟
    private $ratoken = 'l1TjNHfpFNWh6nTRT274M3659yXGTpyYfOF7mIIaRCqn4S4iOV/SX3eST/RUW/AxuLmH6AEuDZxpzLDOo0u1Vj0HG/NsiNeQnCk4SID25Lc=';
    //三方授权token
    private $aticket = "tMlB58ec3I7ChEzkGe33yZQcIBVcGCSbOgfzyPBzy6RPlqwFPrTRcywXEwgEG-3M69ak5Ne7EuCmRhGujX93eN9c32XP9o8hGYmRPwuRlEc.";
    //用户token
    private $uuticket = "dmoQqZDYr4lGem9nfLgfXNMFhw6T6fTyX_RSRllBsEB7lo9Lht_CN-Xwa3G3yVS02J0JSw..";


    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->client = $this->container->get(ClientFactory::class)->create([
            'timeout' => 5.0,
        ]);
        $this->redis = $this->container->get(Redis::class);
        parent::__construct('jst');
    }

    public function configure()
    {
        error_reporting(E_ALL ^ E_WARNING);
        parent::configure();
        $this->setDescription('北京积水潭医院抢号');
    }

    public function handle()
    {
        $i = 1;
        while($i <= 10) {
            go(function() {
                $this->goOrder();
            });
            $i++;
        }
    }

    public function goOrder() {
        $apiResponse = $this->fetchAppointments();
        dump($apiResponse);
        if ($apiResponse['code'] != 0) {
           return;
        }
        $list = $apiResponse['data']['list'];
        foreach ($list as $item) {
            //号源
            if (!empty($item['sourceList'])) {
                //具体号
                foreach ($item['sourceList'] as $source) {
                    //可预约
                    if (!empty($source['supportTimeInterval'])) {
                        $intervals = $this->getInterval($item['periodType'], $source['deptCode'], $source['doctorCode'], $source['sourceCode']);
                        if (!empty($intervals['data']['list'])) {
                            $interval = $intervals['data']['list'][0];
                            dump($this->locking($source['sourceCode'], $source['deptCode'], $source['doctorCode'], $item['periodType'], $interval['timeIntervalCode']));
                            break;
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取脊柱外科科室当天就诊医生列表
     * @return array
     */
    private function fetchAppointments(): array
    {
        $url = sprintf("https://aceso.bjhsyuntai.com/api/mobile/source/dept/detail?_t=%d&deptCode=%d&visitDate=%s&",
            time() * 1000,
            $this->dept_code,
            $this->visit_date
        );
        $response = $this->client->request('GET', $url, [
            'headers' => $this->getHeaders()
        ]);
        return json_decode($response->getBody()->getContents(), true);
    }

    //获取可用时间
    private function getInterval($periodType, $deptCode, $doctorCode, $sourceCode) {
        $url = sprintf("https://aceso.bjhsyuntai.com/api/mobile/source/time/intervals?_t=%d&periodType=%s&deptCode=%d&doctorCode=%d&visitDate=%s&sourceCode=%s",
            time() * 1000,
            $periodType,
            $deptCode,
            $doctorCode,
            $this->visit_date,
            $sourceCode,
        );
        $response = $this->client->request('GET', $url, [
            'headers' => $this->getHeaders()
        ]);
        return json_decode($response->getBody()->getContents(), true);
    }

    //锁单
    private function locking($source_code, $dept_code, $doctor_code, $treatment_period_type, $time_interval): array
    {
        $url = "https://aceso.bjhsyuntai.com/api/mobile/source/locking";
        $response = $this->client->request('POST', $url, [
            'headers' => $this->getHeaders(),
            'json' => [
                'patientCode' => $this->patient_code,
                'sourceCode' => $source_code,
                'deptCode' => $dept_code,
                'doctorCode' => $doctor_code,
                'treatmentDate' => $this->visit_date,
                'treatmentPeriodType' => $treatment_period_type,
                'timeIntervalCode' => $time_interval,
            ],
        ]);
        return json_decode($response->getBody()->getContents(), true);
    }

    private function getHeaders() {
        return [
            'Host' => 'aceso.bjhsyuntai.com',
            'Connection' => 'keep-alive',
            'content-type' => 'application/json;charset=UTF-8',
            'R-A-Token' => $this->ratoken,
            'A-Ticket' => $this->aticket,
            'Hos-Code' => '02110001',
            'U-U-Ticket' => $this->uuticket,
            'Client-Channel' => 'WECHAT_MP',
            'App-Code' => '02110001_HUANZHEDUAN',
            'Accept-Encoding' => 'gzip,compress,br,deflate',
            'User-Agent' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.50(0x1800323b) NetType/WIFI Language/zh_CN',
            'Referer' => 'https://servicewechat.com/wx8dd7d6fe6d5dda8a/45/page-frame.html',
        ];
    }
}
